package com.app.service.impl;

import com.app.common.enums.DataStatusEnum;
import com.app.dao.GoodsRepository;
import com.app.entity.Goods;
import com.app.service.IGoodsService;
import com.app.bean.vo.GoodsVO;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @autor xiaoyu.fang
 * @date 2019/10/11 17:04
 */
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Override
    public void insert(Goods goods) {
        // 价格单位转化为分
        BigDecimal price = new BigDecimal(goods.getPrice() == null ? "0" : goods.getPrice());
        BigDecimal originalPrice = new BigDecimal(goods.getOriginalPrice() == null ? "0" : goods.getOriginalPrice());
        goods.setPrice(String.valueOf(price.setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue()));
        goods.setOriginalPrice(String.valueOf(originalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue()));
        goods.setCreateAt(new Date());
        goods.setDataStatus(DataStatusEnum.VALID.KEY);
        goodsRepository.insert(goods);
    }

    @Override
    public Goods get(ObjectId id) {
        Goods goods = goodsRepository.findById(id).orElse(null);
        if (goods != null) {
            goods.setPrice(new BigDecimal(goods.getPrice()).divide(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            goods.setOriginalPrice(new BigDecimal(goods.getOriginalPrice()).divide(new BigDecimal(100)).stripTrailingZeros().toPlainString());
        }
        return goods;
    }

    @Override
    public List<GoodsVO> queryTop3Frontline(Integer type) {
        List<Goods> goodsList = goodsRepository.queryTop3Frontline(type);
        List<GoodsVO> goodsVOList = new ArrayList<>();
        if (goodsList != null && goodsList.size() > 0) {
            goodsList.stream().forEach(goods -> goodsVOList.add(GoodsVO.getGoodsVO(goods)));
        }
        return goodsVOList;
    }
}
